package com.drollo77.idespensa;

import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class BorraProductos extends Activity {
	
	private DespensaDbAdapter borraDbHelper;
	private WebServiceComms webservice;
	private Long mRowId;
	private Boolean resultado;
	
	private ProgressBar progresoSinc;
	private TextView tituloBorrar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.d("borra producto","Entra en borra producto");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.borra_producto);
        Log.d("borra producto","Cargado layout");
        // Inicializar la base de datos
		borraDbHelper = new DespensaDbAdapter(this);
        borraDbHelper.open();
        Log.d("borra producto","Cargado BBDD");
        
        //Inicializar webservice
        webservice = new WebServiceComms(this);
        
        // Inicializar las variables donde se guardaran los valores del UI  
        Log.d("borra producto","Inicializados controles");
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        mRowId = extras.getLong(DespensaDbAdapter.KEY_PR_ROWID);
        Log.d("borra producto","Producto a borrar: " + mRowId.toString());
        
        //Inicializa controles interfaz
        
        progresoSinc = (ProgressBar) findViewById(R.id.borrarProgreso); 
        tituloBorrar = (TextView) findViewById(R.id.tituloBorrar);
        progresoSinc.setVisibility(ProgressBar.INVISIBLE);
        tituloBorrar.setVisibility(TextView.INVISIBLE);
        
        resultado = null;
        
        borraProductos();
    }

    @Override
	protected void onPause() {
		super.onPause();
		if(!borraDbHelper.transaccion_activa()){
			borraDbHelper.close();
			Log.e("borra producto", "Cierra BBDD");
		}
		Log.i("borra producto","Pausa de actividad");
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Log.i("borra producto","Retorna a actividad");
		if(!borraDbHelper.transaccion_activa()){
			Log.w("borra producto","Borra producto abre BBDD");
			borraDbHelper.open();
		}		
	}
	
	@Override
    protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
    }
	
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
	  super.onRestoreInstanceState(savedInstanceState);
	  // Restore UI state from the savedInstanceState.
	  // This bundle has also been passed to onCreate.
	}
	
	protected class WebServiceComms extends AsyncTask<String, Integer, String>{
    	
    	private Context mCtx;
    	private String result;
    	private HttpUrlConnection request;
    	private String device_id;
    	private AccountManager am;
    	private Account[] accounts;
    	private String user_id;
    	private URL url;
    	private final String strurl = "http://alkala.no-ip.org/idespensa_service/idespensa_service.php";
    	
    	public WebServiceComms (Context c){
    		mCtx = c;
    		request = new HttpUrlConnection();
    		device_id = Secure.getString(c.getContentResolver(), Secure.ANDROID_ID);
    		
    		am = AccountManager.get(mCtx); // "this" references the current Context
            accounts = am.getAccountsByType("com.google");

    		user_id = accounts[0].name;
    		
    		try{
    			url = new URL(strurl);
    		}catch (Exception e){
    			Log.d("url_creacion","URL de sitio remoto mal formada " + e.getMessage());
    		}
    		Log.i("webservice_init","El Id del dispositivo es: " + device_id);
    		Log.i("webservice_init","El id del usuario es: " + user_id);
    	}
    	
    	
    	private void sincronizaBorraProducto (String producto_id){
    		try{
    			String data;
    			JSONObject datos = new JSONObject();
    			datos.put("producto_id", producto_id);
    			data = "accion=" + URLEncoder.encode("borra_producto","UTF-8")+
    					"&nombre="+URLEncoder.encode(user_id,"UTF-8")+
    					"&datos="+URLEncoder.encode(datos.toString() );
    			result=request.sendPost(url, data);
    		}catch (Exception e){
    			Log.d("webservice_borra_producto","Error actualizando la BBDD remota: " + e.getMessage());
    		}
    	}
    	
    	@Override
    	protected String doInBackground(String... params) {
    		Log.d("webservice","Entra en asynctask");
    		progresoSinc.setVisibility(ProgressBar.VISIBLE);
    		tituloBorrar.setVisibility(TextView.VISIBLE);
    		sincronizaBorraProducto(params[0]);
    		
    		return null;
    	}

    	@Override
    	protected void onPostExecute(String results) {
    		// TODO Auto-generated method stub
    		super.onPostExecute(result);
    		//parse json data
    		try{
    			if(result != null){
    				JSONObject json_result = new JSONObject(result);
    				Log.d("json_parsing","Numero de elementos en JSON: " + json_result.length());
    				Iterator<?> iter = json_result.keys();
    				while(iter.hasNext()){
				        String key = (String)iter.next();
				        if(key.equals("error")){
				        	Toast.makeText(mCtx, "Error: " + json_result.getString(key), Toast.LENGTH_SHORT).show();
				        	setResult(RESULT_CANCELED);
				        	resultado = false;
				        }else{
				        	Toast.makeText(mCtx, key + " actualizado: " + json_result.getString(key), Toast.LENGTH_SHORT).show();
				        	Log.d("json_parsing","Borrado sincronizado");
				        	setResult(RESULT_OK);
				        	resultado = true;
				        }				        
				    }
    			}else{
    				Toast.makeText(mCtx, "No se ha obtenido respuesta ", Toast.LENGTH_LONG).show();
    				Log.e("json_parsing","No se ha obtenido respuesta");
    				setResult(RESULT_CANCELED);
		        	resultado = false;
    			}
    			
				borraDbHelper.fin_transaccion(resultado);
				progresoSinc.setVisibility(ProgressBar.INVISIBLE);
				tituloBorrar.setVisibility(TextView.INVISIBLE);
				borraDbHelper.close();
   		        
    		}catch(JSONException e){
    		        Log.e("json_parsing", "Error parsing data "+e.toString());
    		}finally{
    			borraDbHelper.close();
    			finish();
    		}
    	}

    }
	
	
	public void borraProductos() {
		if(mRowId!=null){
			borraDbHelper.inicia_transaccion();
			if(borraDbHelper.borraProducto(mRowId)){
				webservice.execute(mRowId.toString());
				Toast.makeText(this, "Producto borrado", Toast.LENGTH_SHORT).show();				
			}else{
				Toast.makeText(this, "El producto no existe", Toast.LENGTH_LONG).show();
				borraDbHelper.fin_transaccion(false);
				setResult(RESULT_CANCELED);
				finish();
			}
		}else{
			Toast.makeText(this, "El producto no existe, creelo nuevo", Toast.LENGTH_LONG).show();
			setResult(RESULT_CANCELED);
			finish();
		}
		
	}
		
}
